#include "videoview.h"
#include <QGraphicsProxyWidget>
#include <QVideoSurfaceFormat>
#include "mjpegfile.h"

VideoView::VideoView(QDeclarativeItem *parent) :
    QDeclarativeItem(parent), _videoFormatInitialized(false)
{
    _widget = new VideoWidget();
    _proxy = new QGraphicsProxyWidget(this);
    _proxy->setWidget(_widget);

    connect(this, SIGNAL(widthChanged()), this, SLOT(onGeometryChanged()));
    connect(this, SIGNAL(heightChanged()), this, SLOT(onGeometryChanged()));
}

VideoView::~VideoView()
{
    delete _widget;
}

QObject *VideoView::videoFeed()
{
    return _widget;
}

void VideoView::setVideoFeed(QObject *videoFeed)
{
    _mjpegFile = videoFeed;

    connect(dynamic_cast<MJpegFile*>(_mjpegFile), SIGNAL(imageReceived(QImage*)), this, SLOT(onImageReceived(QImage*)));
}

void VideoView::onImageReceived(QImage *image)
{
    QVideoFrame frame(*image);
    if (_videoFormatInitialized == false)
    {
        _videoFormatInitialized = true;
        QVideoSurfaceFormat format = QVideoSurfaceFormat(image->size(), frame.pixelFormat());
        _widget->videoSurface()->start(format);
    }
    _widget->videoSurface()->present(frame);
    delete image;
}

void VideoView::onGeometryChanged()
{
    QRect rect(0, 0, width(), height());
    _widget->setGeometry(rect);
}

void VideoView::onVideoTimeout()
{
    _widget->videoSurface()->stop();
    _videoFormatInitialized = false;
}
